using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Coldairarrow.Util;

namespace Coldairarrow.Business.Cache
{
  class TokenCache : ITokenCache, ITransientDependency
  {
    readonly IDistributedCache _cache;
    public TokenCache(IDistributedCache cache)
    {
      _cache = cache;
    }

    #region 私有成员
    protected string BuildKey(string idKey)
    {
      return $"Cache_{GetType().FullName}_{idKey}";
    }

    #endregion

    public string CreateToken(string userId)
    {
      string str = userId + DateTime.Now.ToString("yyyyMMddHHmmss")+Guid.NewGuid().ToString();
      return str.ToMD5String();
    }

    public async Task<string> GetTokenCacheAsync(string token)
    {
      if (token.IsNullOrEmpty())
        return null;
      string cacheKey = BuildKey(token);
      var cache = await _cache.GetStringAsync(cacheKey);
      return cache;
    }

    public async Task SetTokenCacheAsync(string token, string userid, TimeSpan timeSpan)
    {
      if (token.IsNullOrEmpty())
        throw new ArgumentNullException("idKey is Null");
      string cacheKey = BuildKey(token);
      DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();
      options.AbsoluteExpirationRelativeToNow = timeSpan;
      await _cache.SetStringAsync(cacheKey, userid, options);
    }

    public async Task RemoveAsync(string token)
    {
      await _cache.RemoveAsync(BuildKey(token));
    }

    public async Task RemoveAsync(List<string> tokens)
    {
      foreach (var aKey in tokens)
      {
        await RemoveAsync(aKey);
      }
    }
  }
}
